Soru & Cevap

swift 3 firibase notification kapalı iken gelmiyor.

18.03.2017 - 01:38

siwift 3 te firibase ile bildirim işlemi yapmaya çalışıyorum. sertifika imzasını yaptım. Kodlarım bunlar.

//
//  AppDelegate.swift
//  Ornek
//
//  Created by Cemil Yeşil on 17.03.2017.
//  Copyright © 2017 Haber. All rights reserved.
//

import UIKit

import UserNotifications

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
            
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self
            
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
        application.registerForRemoteNotifications()

        // [END register_for_notifications]
        FIRApp.configure()
        
        // [START add_token_refresh_observer]
        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)
        // [END add_token_refresh_observer]
        return true
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification
        // Print message ID.
        
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

        print("ikinci notification:")
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        
        
        application.registerForRemoteNotifications()
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification),
                                               name: .firInstanceIDTokenRefresh,
                                               object: nil)
        var turr = ""
        var baslikk = ""
        var ozett = ""
        var icerikk = ""
        var resimm = ""
        var idd = ""
        
        
        if let tur = userInfo["tur"] as? String  {
            print(tur)
            turr = tur
        }
        if let id = userInfo["id"] as? String  {
            print(id)
            idd = id
        }
        if let baslik = userInfo["baslik"] as? String  {
            print(baslik)
            baslikk = baslik
        }
        if let ozet = userInfo["ozet"] as? String  {
            print(ozet)
            ozett = ozet
        }
        if let icerik = userInfo["icerik"] as? String  {
            print(icerik)
            icerikk = icerik
        }
        if let resim = userInfo["resim"] as? String  {
            print(resim)
            resimm = resim
            
        }
        if turr=="bildirim" {
            var databasePath = String()
            let filemgr = FileManager.default
            let dirPaths = filemgr.urls(for: .documentDirectory,
                                        in: .userDomainMask)
            
            databasePath = dirPaths[0].appendingPathComponent("haberler.db").path
            let contactDB = FMDatabase(path: databasePath as String)
            
            if (contactDB?.open())! {
                let date = Date()
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy.MM.dd"
                let tarih = formatter.string(from: date)
                
                
                let insertSQL = "INSERT INTO haberler (baslik, ozet, icerik, img, tarih,tur) VALUES ('"+baslikk+"', '"+ozett+"', '"+icerikk+"', '"+resimm+"', '"+tarih+"', '"+turr+"')"
                
                let result = contactDB?.executeUpdate(insertSQL,
                                                      withArgumentsIn: nil)
                
                if result! {
                    
                    print("Ok: kayıt yapıldı")
                }
            } else {
                print("Error: \(contactDB?.lastErrorMessage())")
            }
            
        }
        let alert = UIAlertController(title: baslikk, message: ozett, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Kapat", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Aç", style: .default, handler:
            { action in
                switch action.style {
                case .default:
                    var databasePath = String()
                    let filemgr = FileManager.default
                    let dirPaths = filemgr.urls(for: .documentDirectory,
                                                in: .userDomainMask)
                    
                    databasePath = dirPaths[0].appendingPathComponent("haberler.db").path
                    let contactDB = FMDatabase(path: databasePath as String)
                    
                    if (contactDB?.open())! {
                        let querySQL = "SELECT * FROM haberler  "
                        
                        let results:FMResultSet? = contactDB?.executeQuery(querySQL,
                                                                           withArgumentsIn: nil)
                        if results?.next() == true {
                            while (results?.next())! {
                                idd=(results?.string(forColumn: "id"))!
                            }
                        }
                        
                        
                        
                        contactDB?.close()
                    } else {
                        print("Error: \(contactDB?.lastErrorMessage())")
                    }
                    
                    let vc = self.window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "Haber_Detay") as! Haber_Detay
                    vc.imageString = resimm
                    vc.ozet = ozett
                    vc.id = idd
                    vc.tur = turr
                    vc.icerik = icerikk
                    
                    
                    self.window?.rootViewController = vc
                    
                    
                    break
                case .cancel: break
                case .destructive: break
                    
                }
        }))
        
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
        
        // Print full message.
        print(userInfo)
        
        completionHandler(UIBackgroundFetchResult.newData)
      
    }
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        // Let FCM know about the message for analytics etc.
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)
        
        print("enson")
        // handle your message
    }
    
        // [START receive_message]
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            // If you are receiving a notification message while your app is in the background,
            // this callback will not be fired till the user taps on the notification launching the application.
            // TODO: Handle data of notification
            // Print message ID.
            FIRMessaging.messaging().appDidReceiveMessage(userInfo)
            guard let aps = userInfo["aps"] as? [String : AnyObject] else {
                print("Error parsing aps")
                return
            }
            let name:NSNotification.Name = NSNotification.Name("notificationName")
            NotificationCenter.default.post(name: name, object: nil)
            var body = ""
            var title = "20Fit"
            if let alert = aps["alert"] as? String {
                body = alert
            } else if let alert = aps["alert"] as? [String : String] {
                body = alert["body"]!
                title = alert["title"]!
            }
            
           
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
  
    
    application.registerForRemoteNotifications()
     
    NotificationCenter.default.addObserver(self,
    selector: #selector(self.tokenRefreshNotification),
    name: .firInstanceIDTokenRefresh,
    object: nil)

            print("birinci notification:")
            var turr = ""
            var baslikk = ""
            var ozett = ""
            var icerikk = ""
            var resimm = ""
            var idd = ""
            
            
            if let tur = userInfo["tur"] as? String  {
                print(tur)
                turr = tur
            }
            if let id = userInfo["id"] as? String  {
                print(id)
                idd = id
            }
            if let baslik = userInfo["baslik"] as? String  {
                print(baslik)
                baslikk = baslik
            }
            if let ozet = userInfo["ozet"] as? String  {
                print(ozet)
                ozett = ozet
            }
            if let icerik = userInfo["icerik"] as? String  {
                print(icerik)
                icerikk = icerik
            }
            if let resim = userInfo["resim"] as? String  {
                print(resim)
                resimm = resim
                
            }
            if turr=="bildirim" {
                var databasePath = String()
                let filemgr = FileManager.default
                let dirPaths = filemgr.urls(for: .documentDirectory,
                                            in: .userDomainMask)
                
                databasePath = dirPaths[0].appendingPathComponent("haberler.db").path
                let contactDB = FMDatabase(path: databasePath as String)
                
                if (contactDB?.open())! {
                    let date = Date()
                    let formatter = DateFormatter()
                    formatter.dateFormat = "yyyy.MM.dd"
                    let tarih = formatter.string(from: date)
                    
                    
                    let insertSQL = "INSERT INTO haberler (baslik, ozet, icerik, img, tarih,tur) VALUES ('"+baslikk+"', '"+ozett+"', '"+icerikk+"', '"+resimm+"', '"+tarih+"', '"+turr+"')"
                    
                    let result = contactDB?.executeUpdate(insertSQL,
                                                          withArgumentsIn: nil)
                    
                    if result! {
                        
                        print("Ok: kayıt yapıldı")
                    }
                } else {
                    print("Error: \(contactDB?.lastErrorMessage())")
                }
                
            }
            let alert = UIAlertController(title: baslikk, message: ozett, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Kapat", style: .cancel, handler: nil))
            alert.addAction(UIAlertAction(title: "Aç", style: .default, handler:
                { action in
                    switch action.style {
                    case .default:
                        var databasePath = String()
                        let filemgr = FileManager.default
                        let dirPaths = filemgr.urls(for: .documentDirectory,
                                                    in: .userDomainMask)
                        
                        databasePath = dirPaths[0].appendingPathComponent("haberler.db").path
                        let contactDB = FMDatabase(path: databasePath as String)
                        
                        if (contactDB?.open())! {
                            let querySQL = "SELECT * FROM haberler  "
                            
                            let results:FMResultSet? = contactDB?.executeQuery(querySQL,
                                                                               withArgumentsIn: nil)
                            if results?.next() == true {
                                while (results?.next())! {
                                    idd=(results?.string(forColumn: "id"))!
                                }
                            }
                            
                            
                            
                            contactDB?.close()
                        } else {
                            print("Error: \(contactDB?.lastErrorMessage())")
                        }
                        
                        let vc = self.window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "Haber_Detay") as! Haber_Detay
                        vc.imageString = resimm
                        vc.ozet = ozett
                        vc.id = idd
                        vc.tur = turr
                        vc.icerik = icerikk
                        
                        
                        self.window?.rootViewController = vc
                        
                        
                        break
                    case .cancel: break
                    case .destructive: break
                        
                    }
            }))
            
            self.window?.rootViewController?.present(alert, animated: true, completion: nil)
            
            // Print full message.
            print(userInfo)
 
        }
        
 
        // [START refresh_token]
        func tokenRefreshNotification(_ notification: Notification) {
            if let refreshedToken = FIRInstanceID.instanceID().token() {
                print("InstanceID token: \(refreshedToken)")
            }
                     // Connect to FCM since connection may have failed when attempted before having a token.
            connectToFcm()
        }
  
  

        // [END refresh_token]
        // [START connect_to_fcm]
        func connectToFcm() {
            // Won't connect since there is no token
            guard FIRInstanceID.instanceID().token() != nil else {
                return
            }
            
            // Disconnect previous FCM connection if it exists.
            FIRMessaging.messaging().disconnect()
            
            FIRMessaging.messaging().connect { (error) in
                if error != nil {
                    print("Unable to connect with FCM. \(error)")
                } else {
                    let device_id = UIDevice.current.identifierForVendor as Any
                    let uuid = UIDevice.current.identifierForVendor?.uuidString
                    print("uuid : " + uuid!)
                    let token =  FIRInstanceID.instanceID().token()
                    if token != nil{
                        print("token_id" + token!)

                    let dict = ["device":uuid! ,"token":token! ] as [String: Any]
                    
                    if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
                        let url = URL(string: "http://kardessuriye.com/app-json/ios_token_kaydet.php")!
                        let request = NSMutableURLRequest(url: url as URL)
                        request.httpMethod = "POST"
                        request.httpBody = jsonData
                        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                        let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
                            if error != nil{
                                print(error?.localizedDescription)
                                return
                            }
                            do {
                                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                                if let parseJSON = json {
                                    
                                    
                                    
                                }
                            } catch let error as NSError {
                                print(error)
                            }
                        }
                        task.resume()
                        }
                    }
                    else{
                    print("token boş")
                    }

                    print("Connected to FCM.")
                }
            }
        }
    
        // [END connect_to_fcm]
        func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
            print("Unable to register for remote notifications: \(error.localizedDescription)")
        }
        
        // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
        // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
        // the InstanceID token.
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
        var token = ""
        
        for i in 0..<deviceToken.count {
            token += String(format: "%02.2hhx", arguments: [chars[i]])
        }
        
          FIRInstanceID.instanceID().setAPNSToken(deviceToken, type:FIRInstanceIDAPNSTokenType.sandbox)
          FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
          FIRInstanceID.instanceID().setAPNSToken(deviceToken, type:FIRInstanceIDAPNSTokenType.prod)
        
        print("Device Token = ", token)
    }
  
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        
        
        FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.unknown)
         
    }
        // [START connect_on_active]
        func applicationDidBecomeActive(_ application: UIApplication) {
            
            connectToFcm()
            
           application.applicationIconBadgeNumber = 0;
        }
        // [END connect_on_active]
        // [START disconnect_from_fcm]
        func applicationDidEnterBackground(_ application: UIApplication) {
           FIRMessaging.messaging().disconnect()
            print("Disconnected from FCM.")
        }
        // [END disconnect_from_fcm]
    
    static func registerForPushNotifications() {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
         UIApplication.shared.registerUserNotificationSettings(settings)
        UIApplication.shared.registerForRemoteNotifications()
    }
    
    }
    
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    
    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
      
        
        // Print full message.
        print(userInfo)
        
        // Change this to your preferred presentation option
        completionHandler([])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
      
        
        // Print full message.
        print(userInfo)
        
        completionHandler()
    }
}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices while app is in the foreground.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print(remoteMessage.appData)
    }
}
// [END ios_10_data_message_handling]

 

appdelegate kodlarım yukarda  kullanıyrum. Ancak uygulama firibase consolundan mesaj attığımda uygulama açıkta olsa kapalıda olsa normal çalışıyor. bildirim geliyor.
Php dosyasından attığımda 


<?php
if(isset($_POST['submit'])){//kontrol
   
        
  $token_idler = array(); 
    
$data = array('id'=> "0", 'priority' => "high",'tur'=> "bildirim",'title'=>$_POST['baslik'],'baslik'=>$_POST['baslik'],'ozet'=> $_POST['ozet'] ,'icerik'=>$_POST['icerik'],'resim'=>$_POST['resim']);
      
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'serverapi_key';
            
$fields = array();
$fields['data'] = $data;
if(is_array(  "token_id")){
    $fields['token_idler'] =   "token_id";
}else{
    $fields['to'] = "token_id";
}
//header with content_type api key
$headers = array(
    'Content-Type:application/json',
  'Authorization:key='.$server_key
);
            
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
         
}
?>

 

Php kodları yukarda. bildirim uygulama açıkken geliyor ayrıştırıyorum. fakat uygulama kapalı iken bildirim gelmiyor. bunun çözümünu araştırıyoruma am birtürlü bulamadım. böyle bi durumla karşıalşan varmı ? 

 

yani kısıacası firibase apisini kullanıyorum. uygulama açıkken bildirim alert olarak alıyorum. ama uygulama kapalı iken hiçbir şekilde bildirm gelmiyor. uygualmayı açınca alert oalrak geliyor.

8 Görüntülenme

0 Cevap

Sitedeki sorulara cevap verebilmek için giriş yapın ya da üye olun.